package com.android.superobstacleavoider;

import java.util.Random;

import javax.microedition.khronos.opengles.GL10;

public class BallCollection {

	private final static int MAX_BALLS = 5;
	private Ball[] m_balls;
	private ModelData m_sphereModel;
	private float m_spawnTime;
	private float m_timeMultiplier;
	private static Random m_rnd = new Random();
	private float m_timeSinceLastSpawn;
	private int m_newScore;
	private int m_id;

	public int getNewScore() {
		return m_newScore;
	}

	public BallCollection() {
		initialize();
	}

	public void setModel(ModelData model) {
		m_sphereModel = model;
	}

	public void initialize() {
		m_balls = new Ball[MAX_BALLS];

		switch (Game.getDifficulty()) {
		case 0:
			m_timeMultiplier = 30.0f;
			break;
		case 1:
			m_timeMultiplier = 40.0f;
			break;
		case 2:
			m_timeMultiplier = 50.0f;
			break;
		}
		m_timeSinceLastSpawn = 0.0f;
		m_id = 0;

		// skapar alla hinder till banan
		for (int i = 0; i < m_balls.length; i++) {
			m_balls[i] = new Ball(i);
		}
	}

	public void update(float a_dt, Player a_player, int a_score) {
		m_newScore = a_score;
		m_spawnTime = ((float) m_rnd.nextFloat() * m_timeMultiplier);
		if (m_timeSinceLastSpawn >= m_spawnTime) {
			m_balls[m_id].spawn();
			m_timeSinceLastSpawn = 0.0f;
			m_id += 1;
			
			if (m_id >= MAX_BALLS) {
				m_id = 0;
			}
		}
		else {
			m_timeSinceLastSpawn += a_dt;
		}

		for (Ball o : m_balls) {

			if (o.isAlive()) {
				o.update(a_dt);
				
				if (o.getSphere().sphereIntersects(a_player.getSphere())
						&& !o.getcollideWithPlayer()) {
					o.setcollideWithPlayer(true);
					m_newScore += 100;
					AudioHandler.playSound(AudioHandler.getBallSound());
					o.setIsAlive(false);
				} 
			}
		}
	}

	public void draw(GL10 gl) {
		// draw obstacles
		for (Ball o : m_balls) {
			if (o.isAlive() && !o.getcollideWithPlayer()) {
				ModelHandler.drawModel(gl, m_sphereModel, new Vector3(0.00015f,
						0.00015f, 0.00015f), o.getPosition(), null, 0, true);
			}
		}
	}

}
